from django.http import JsonResponse
from .models import Book

# 查询所有
def get_books(request):
    if request.method == 'GET':
        books_data= Book.get_all()
        return JsonResponse({'books': books_data})
    else:
        return JsonResponse({'error': 'Method not allowed'}, status=405)

#用id查询
def get_book(request, book_id):
    if request.method == 'GET':
        book_data = Book.get_book(book_id)
        if book_data:
            return JsonResponse({'book': book_data})
        else:
            return JsonResponse({'error': '未找到该书籍'}, status=404)
    else:
        return JsonResponse({'error': 'Method not allowed'}, status=405)


def add_book(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        author = request.POST.get('author')
        if title and author:
            book_created = Book.create_book(title, author)
            if book_created:
                return JsonResponse({'message': '添加成功'})
            else:
                return JsonResponse({'error': '无法添加'}, status=500)
        else:
            return JsonResponse({'error': '标题和作者是必填项'}, status=400)
    else:
        return JsonResponse({'error': 'Method not allowed'}, status=405)

# 修改
def update_book(request, book_id):
    if request.method == 'POST':
        title = request.POST.get('title')
        author = request.POST.get('author')
        success = Book.update_book(book_id, title, author)
        if success:
            return JsonResponse({'message': '修改成功'})
        else:
            return JsonResponse({'error': '未找到该书籍'}, status=404)
    else:
        return JsonResponse({'error': 'Method not allowed'}, status=405)

# 删除
def delete_book(request, book_title):
    if request.method == 'DELETE':
        success = Book.delete_book(book_title)
        if success:
            return JsonResponse({'message': '删除成功'})
        else:
            return JsonResponse({'error': '未找到该书籍'}, {'code':404})
    else:
        return JsonResponse({'error': 'Method not allowed'}, status=405)
